package com.hilin.etcd.client;

import com.hilin.common.util.EntityUtils;
import io.netty.handler.ssl.SslContext;
import lombok.SneakyThrows;
import mousio.etcd4j.EtcdClient;
import mousio.etcd4j.EtcdSecurityContext;
import mousio.etcd4j.responses.EtcdAuthenticationException;
import mousio.etcd4j.responses.EtcdException;
import mousio.etcd4j.transport.EtcdClientImpl;

import java.io.IOException;
import java.net.URI;
import java.util.concurrent.TimeoutException;

public class HilinEtcdClient extends EtcdClient {

    public HilinEtcdClient(URI... baseUri) {
        super(baseUri);
    }

    public HilinEtcdClient(String username, String password, URI... baseUri) {
        super(username, password, baseUri);
    }

    public HilinEtcdClient(SslContext sslContext, String username, String password, URI... baseUri) {
        super(sslContext, username, password, baseUri);
    }

    public HilinEtcdClient(SslContext sslContext, URI... baseUri) {
        super(sslContext, baseUri);
    }

    public HilinEtcdClient(EtcdSecurityContext securityContext, URI... baseUri) {
        super(securityContext, baseUri);
    }

    public HilinEtcdClient(EtcdClientImpl etcdClientImpl) {
        super(etcdClientImpl);
    }

    /**********************************************
     *                拓展的方法                    *
     **********************************************/
    /**
     * 加锁
     *
     * @param key
     */
    @SneakyThrows
    public boolean tryLock(String key, Integer ttl) {
        return tryLock(key, "1", ttl);
    }

    @SneakyThrows
    public boolean tryLock(String key, String value, Integer ttl) {
        try {
            put(key, value).prevExist(false).ttl(ttl).send().get();
            return true;
        } catch (EtcdException e) {
            if (e.errorCode == 105) {
                return false;
            }
            throw e;
        }
    }

    /**
     * 解锁
     *
     * @param key
     */
    public void unlock(String key) {

    }

    public static void main(String[] args) {
        HilinEtcdClient client = new HilinEtcdClient(URI.create("http://localhost:2379"));
        for (int i = 0; i < 10; i++) {
            try {
                System.out.println(EntityUtils.toJsonString(client.put("key", "value")
                        .prevValue("")
                        .prevExist(false).ttl(30).send().get()));
            } catch (EtcdException | IOException | EtcdAuthenticationException | TimeoutException e) {
                e.printStackTrace();
            }
        }
    }

}
